#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<string.h>


#define N 10

int main()
{
    int j = 0;
    std::vector<pid_t> v;
    for(j = 0; j < N; j++)
    {
        pid_t pid = fork();

        if(pid == 0)
        {
            int i = 0;
            while(1)
            {
                printf("我是子进程，pid = %d, ppid = %d, count = %d\n", getpid(), getppid(), i);
                sleep(3);
                //int a = 10;
                //a /= 0;
                //int* p = NULL;
                //*p = 10;
                sleep(1);
                break;
            }
            printf("子进程退出了！\n");

            //exit(0);
            int ret = 1;
            if(ret == 0)
            {
                exit(0);
            }
            else 
            {
                exit(1);
            }
            
        }
        v.push_back(pid);
    }    
    
    sleep(5);

    for(auto& e : v)
    {
        printf("父进程正在等待中...%d\n", e);
        //pid_t ret_pid = wait(NULL);
        int status = 0;
        pid_t ret_pid = waitpid(e, &status, 0);

        if(ret_pid > 0)
        {
            int exit_code = (status >> 8) & 0xFF;
            int exit_signal = status & 0x7F;
            if(exit_code == 0 && exit_signal == 0)
            {
                printf("子进程运行完毕，结果正确\n");
            }
            else if(exit_code > 0 && exit_signal == 0)
            {
                printf("子进程运行完毕，结果不正确%d:%s\n", exit_code, strerror(exit_code));
            }
            else
            {
                printf("子进程出现异常，exit_signal = %d\n", exit_signal);
            }
            //printf("父进程等待成功，子进程pid = %d, status = %d, eixt code = %d, exit signal = %d\n", ret_pid, status, (status >> 8) & 0xFF, status & 0x7F);
        }
        else
        {
            printf("wait failed\n");
        }
    }
    sleep(2);

    return 0;
}
